package com.hospital.workstation.webService.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Console;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.introspect.VirtualAnnotatedMember;
import com.hospital.common.core.domain.entity.SysDept;
import com.hospital.common.core.domain.model.LoginUser;
import com.hospital.common.helper.LoginHelper;
import com.hospital.common.utils.JsonUtils;
import com.hospital.common.utils.StringUtils;
import com.hospital.system.mapper.SysDeptMapper;
import com.hospital.system.service.ISysDeptService;
import com.hospital.workstation.constant.DictConstants;
import com.hospital.workstation.domain.*;
import com.hospital.workstation.domain.bo.*;
import com.hospital.workstation.domain.vo.*;
import com.hospital.workstation.mapper.FirstLevelMapper;
import com.hospital.workstation.mapper.PatientBaseInfoMapper;
import com.hospital.workstation.mapper.PharmaceuticalCareDetailMapper;
import com.hospital.workstation.mapper.TwoLevelMapper;
import com.hospital.workstation.service.*;
import com.hospital.workstation.utils.CXFClientUtil;
import com.hospital.workstation.utils.CareLevelUtil;
import com.hospital.workstation.utils.DateUtil;
import com.hospital.workstation.webService.domain.Request;
import com.hospital.workstation.webService.domain.Response;
import com.sun.corba.se.spi.ior.ObjectKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hpsf.Decimal;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.scheduling.support.SimpleTriggerContext;

import javax.sound.sampled.Line;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:HYZ
 * @Date:2023-3-1
 */
@Slf4j
public class SendMessageInfoService {

    /**
     * 患者基本信息
     *
     * @param data
     * @param patientBaseInfoService
     * @return
     */
    public static String PatientRegistry(String data, IPatientBaseInfoService patientBaseInfoService) {
        try {
            Request request = getRequest(data);
            Map body = request.getBody();
            Map patientBody = (Map) body.get("PatientRegistryRt");

            // 封装患者基本信息对象
            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            bo.setPatientNo(String.valueOf(patientBody.get("PATPatientID")));
            // 根据患者ID号查询患者信息列表
            List<PatientBaseInfoVo> patientBaseInfoVoList = patientBaseInfoService.queryList(bo);
            // 患者姓名
            bo.setPatientName(String.valueOf(patientBody.get("PATName")));
            // 患者性别
            bo.setPatientSex(String.valueOf(patientBody.get("PATSexCode")));
            // 民族
            bo.setNation(String.valueOf(patientBody.get("PATNationDesc")));
            // 职业
            bo.setPatientProfession(String.valueOf(patientBody.get("PATOccupationDesc")));
            // 联系方式
            bo.setPhoneNo(String.valueOf(patientBody.get("PATTelephone")));
            // 获取患者出生日期
            String patDob = String.valueOf(patientBody.get("PATDob"));
            if (StringUtils.isNotBlank(patDob)) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Map<String, Integer> birthdayMap = DateUtil.getAgeAndMonthByBirthday(format.parse(patDob));
                // 出生日期
                bo.setBirthdate(format.parse(patDob));
                // 年龄
                bo.setPatientAge(birthdayMap.get("year"));
                // 月份
                bo.setPatientMonth(birthdayMap.get("month"));
            }
            // 设置创建者和更新者为HIS
            bo.setCreateBy("HIS");
            bo.setUpdateBy("HIS");

            // 判断患者基本信息是否已存在，如果存在就更新信息，不存在就新增
            boolean flag = false;
            if (ObjectUtil.isNotNull(patientBaseInfoVoList) && patientBaseInfoVoList.size() > 0) {
                // 批量更新患者基本信息
                flag = patientBaseInfoService.updateBatchByWrapper(bo);
            } else {
                // 患者信息来源（0手工录入 1HIS）
                bo.setSourceInfo("1");
                // 新增
                flag = patientBaseInfoService.insertByBo(bo);
            }

            return flag ? "0" : "1";
        } catch (Exception e) {
            e.printStackTrace();
            return "1";
        }
    }

    /**
     * 患者基本信息
     *
     * @param data
     * @return
     */
    public static String PatientRegistry_bak(String data, IPatientBaseInfoService patientBaseInfoService) {
        try {
            Request request = getRequest(data);
            Map body = request.getBody();
            Map body1 = (Map) body.get("PatientRegistryRt");
//            bodyst = bodyst.replaceAll("=", ":");
//            body = JSONUtil.toBean(bodyst, Map.class);
//            Map body1 = JSONUtil.toBean(bodyst, Map.class);

            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            bo.setPatientNo(String.valueOf(body1.get("PATPatientID")));
//            bo.setPaadmVisitNo(String.valueOf(body1.get("PATDocumentNo")));//paadm_visit_no 就诊号码
            List<PatientBaseInfoVo> patientBaseInfoVos = patientBaseInfoService.queryList(bo);
            // 患者姓名
            bo.setPatientName(String.valueOf(body1.get("PATName")));
//            bo.setAdmissionTime(LocalDateTime.now());//admission_time 入院时间

            bo.setPatientState("0");
//        bo.setPatientName(body.get(""));//discharge_time 出院时间
//        bo.setPatientName(body.get(""));//doctor_id 主管医生ID
//        bo.setPatientName(body.get(""));//bed_no 床号
//        bo.setPatientName(body.get(""));//first_diagnose 第一诊断
//        bo.setPatientName(body.get(""));//guardian_level 监护分级（0一级 1二级 2三级）
//        bo.setPatientName(body.get(""));//patient_state 住院状态（0住院患者 1出院患者）
            String PATSexDesc = String.valueOf(body1.get("PATSexDesc"));
            String sex = "2";
            if (PATSexDesc.contains("男")) {
                sex = "0";
            } else if (PATSexDesc.contains("女")) {
                sex = "1";
            }
            bo.setPatientSex(sex);//patient_sex 患者性别（0男 1女 2未知）
            DateTime patDob = DateUtil.parse(String.valueOf(body1.get("PATDob")));

            List<Long> age = DateUtil.getAge(patDob);

            bo.setPatientAge(age.get(0).intValue());//patient_age 年龄
            bo.setPatientMonth(age.get(1).intValue());//patient_age 年龄
            bo.setBirthdate(DateUtil.parse(String.valueOf(body1.get("PATDob"))));//birthdate 出生日期
            bo.setPatientProfession(String.valueOf(body1.get("PATOccupationDesc")));//patient_profession 职业
            bo.setNation(String.valueOf(body1.get("PATNationDesc")));//nation 民族
//        bo.setPatientName(body.get(""));//patient_height 身高（cm）
//        bo.setPatientName(body.get(""));//patient_weight 体重（kg）
//        bo.setPatientName(body.get(""));//patient_bmi BMI（kg/㎡）
            bo.setPhoneNo(String.valueOf(body1.get("PATRelationPhone")));//phone_no 联系方式
//        bo.setPatientName(body.get(""));//pay_way 付费方式（0支付宝 1微信 2现金）
            bo.setSourceInfo("1");//source_info 患者信息来源（0手工录入 1HIS）
//        bo.setPatientName(body.get(""));//
//        bo.setPatientName(body.get(""));//
            boolean re = false;
            if (patientBaseInfoVos.size() > 0) {
                PatientBaseInfoVo vo = patientBaseInfoVos.get(0);
                bo.setId(vo.getId());
                re = patientBaseInfoService.updateByBo(bo);
            } else {
                re = patientBaseInfoService.insertByBo(bo);
            }
            if (re) {
                return "0";
            } else {
                return "1";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
    }

    /**
     * 住院登记
     *
     * @param data
     * @param patientBaseInfoService
     * @return
     */
    public static String InpatientEncounterStarted(String data, IPatientBaseInfoService patientBaseInfoService,
                                                   IHisAdmittingDiagInfoService hisAdmittingDiagInfoService,
                                                   IHisChangeDepartmentService hisChangeDepartmentService,
                                                   SysDeptMapper deptMapper) {
        try {
            Request request = getRequest(data);
            Map body1 = request.getBody();
            Map patientHospitalInfoMap = (Map) body1.get("InpatientEncounterStartedRt");
            // 封装患者住院信息
            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            // 患者ID号
            bo.setPatientNo(String.valueOf(patientHospitalInfoMap.get("PATPatientID")));
            // 根据患者ID号查询患者基本信息
            List<PatientBaseInfoVo> baseInfoVoList = patientBaseInfoService.queryList(bo);
            // 患者基本信息不存在
            if (ObjectUtil.isNull(baseInfoVoList) || baseInfoVoList.size() == 0) {
                return "1";
            }
            // 患者ID号和就诊号已经存在
            bo.setPaadmVisitNo(String.valueOf(patientHospitalInfoMap.get("PAADMVisitNumber")));
            List<PatientBaseInfoVo> baseInfoVoList2 = patientBaseInfoService.queryList(bo);
            if (baseInfoVoList2.size() > 0) {
                return "0";
            }
            // 根据患者ID号和住院查询基本信息
            PatientBaseInfoBo bo2 = new PatientBaseInfoBo();
            bo2.setPatientNo(String.valueOf(patientHospitalInfoMap.get("PATPatientID")));
            // bo2.setPaadmVisitNo(String.valueOf(patientHospitalInfoMap.get("PAADMVisitNumber")));
            // 设置住院状态为住院
            bo2.setPatientState(DictConstants.IN_PATIENT);
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoService.queryOne(bo2);
            if (ObjectUtil.isNull(patientBaseInfoVo)) { // 新增患者基本信息
                patientBaseInfoVo = baseInfoVoList.get(0);
                // 封装患者基本信息对象
                PatientBaseInfoBo patientBaseInfoBo = new PatientBaseInfoBo();
                patientBaseInfoBo.setPatientNo(patientBaseInfoVo.getPatientNo());
                patientBaseInfoBo.setPatientName(patientBaseInfoVo.getPatientName());
                patientBaseInfoBo.setPatientSex(patientBaseInfoVo.getPatientSex());
                patientBaseInfoBo.setNation(patientBaseInfoVo.getNation());
                patientBaseInfoBo.setPatientProfession(patientBaseInfoVo.getPatientProfession());
                patientBaseInfoBo.setPhoneNo(patientBaseInfoVo.getPhoneNo());
                patientBaseInfoBo.setPatientAge(patientBaseInfoVo.getPatientAge());
                patientBaseInfoBo.setPatientMonth(patientBaseInfoVo.getPatientMonth());
                patientBaseInfoBo.setCreateBy("HIS");
                patientBaseInfoBo.setUpdateBy("HIS");
                // 患者信息来源（0手工录入 1HIS）
                patientBaseInfoBo.setSourceInfo("1");
                // 新增患者基本信息
                patientBaseInfoService.insertByBo(patientBaseInfoBo);
                // 根据患者ID号和住院查询基本信息
                patientBaseInfoVo = patientBaseInfoService.queryOne(bo);
                log.info("住院登记-患者基本信息-新增");
            }
            // 更新患者基本信息
            patientBaseInfoVo = patientBaseInfoService.queryOne(bo2);
            bo = BeanUtil.toBean(patientBaseInfoVo, PatientBaseInfoBo.class);
            // 就诊号码
            bo.setPaadmVisitNo(String.valueOf(patientHospitalInfoMap.get("PAADMVisitNumber")));
            // 科室
            String paadmAdmDeptCode = String.valueOf(patientHospitalInfoMap.get("PAADMAdmDeptCode"));
            if (StringUtils.isNotBlank(paadmAdmDeptCode)) {
                bo.setPaadDeptCode(paadmAdmDeptCode); // HIS科室代码
                SysDept sysDept = deptMapper.selectVoOne(new LambdaQueryWrapper<SysDept>()
                    .eq(SysDept::getDelFlag, "0")
                    .eq(SysDept::getHisDeptCode, paadmAdmDeptCode));
                if (ObjectUtil.isNotNull(sysDept)) {
                    bo.setDeptId(sysDept.getDeptId());
                }
            }
            // 入院日期
            String PAADMStartDate = String.valueOf(patientHospitalInfoMap.get("PAADMStartDate"));
            // 入院时间
            String PAADMStartTime = String.valueOf(patientHospitalInfoMap.get("PAADMStartTime"));
            // 设置入院时间
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            bo.setAdmissionTime(LocalDateTime.parse(PAADMStartDate + " " + PAADMStartTime, dtf));
            // 临床药师名称
            bo.setDoctorName(String.valueOf(patientHospitalInfoMap.get("PAADMAdmitDocDesc")));
            // 床号
            bo.setBedNo(String.valueOf(patientHospitalInfoMap.get("PAADMCurBedNo")));
            // 第一诊断
            Map<String, Object> paadmDiagnoseListMap = (Map) patientHospitalInfoMap.get("PAADMDiagnoseList");
            Map<String, Object> paadmDiagnoseMap = (Map) paadmDiagnoseListMap.get("PAADMDiagnose");
            if ("入院诊断".equals(String.valueOf(paadmDiagnoseMap.get("PADDiagTypeDesc")))) {
                bo.setFirstDiagnose(String.valueOf(paadmDiagnoseMap.get("PADDiagDesc")));
            }
            // 付费方式
            bo.setPayWay(String.valueOf(patientHospitalInfoMap.get("FeeTypeCode")));
            // 入院次数
            bo.setVisitTimes(String.valueOf(patientHospitalInfoMap.get("PAADMVisitTimes")));
            // 护理号
            bo.setMedicareNo(String.valueOf(patientHospitalInfoMap.get("PAPMIMedicare")));
            // 入院病区代码
            bo.setMedicareWardCode(String.valueOf(patientHospitalInfoMap.get("PAADMAdmWardCode")));
            // 设置更新者
            bo.setUpdateBy("HIS");
            patientBaseInfoService.updateByBo(bo);
            log.info("住院登记-患者基本信息—更新");

            Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();
            // 保存或更新入院诊断信息
            HisAdmittingDiagInfoBo diagInfoBo = new HisAdmittingDiagInfoBo();
            if ("入院诊断".equals(String.valueOf(paadmDiagnoseMap.get("PADDiagTypeDesc")))) {
                // 病历号
                diagInfoBo.setMedicalRecordNo(medicalRecordNo);
                // 诊断代码
                diagInfoBo.setDiagCode(String.valueOf(paadmDiagnoseMap.get("PADDiagCode")));
                // 诊断类型
                diagInfoBo.setDiagType(DictConstants.DIAG_TYPE_IN);
                // 诊断描述
                diagInfoBo.setDiagDesc(String.valueOf(paadmDiagnoseMap.get("PADDiagDesc")));
                List<HisAdmittingDiagInfoVo> diagInfoVoList = hisAdmittingDiagInfoService.queryList(diagInfoBo);
                // 诊断医生描述
                diagInfoBo.setDiagDocDesc(String.valueOf(paadmDiagnoseMap.get("PADDiagDocDesc")));
                // 诊断级别
                if ("主要诊断".equals(String.valueOf(paadmDiagnoseMap.get("PADDiagCategory")))) {
                    diagInfoBo.setDiagCategory("1");
                } else if ("次要诊断".equals(String.valueOf(paadmDiagnoseMap.get("PADDiagCategory")))) {
                    diagInfoBo.setDiagCategory("2");
                }
                // 诊断日期
                String PADDiagDate = String.valueOf(paadmDiagnoseMap.get("PADDiagDate"));
                // 诊断时间
                String PADDiagTime = String.valueOf(paadmDiagnoseMap.get("PADDiagTime"));
                // 设置诊断日期时间
                diagInfoBo.setDiagTime(LocalDateTime.parse(PAADMStartDate + " " + PAADMStartTime, dtf));
                // 诊断类型（西医、中医、证型）
                diagInfoBo.setDiagCat(String.valueOf(paadmDiagnoseMap.get("PADDiagCat")));
                // 设置创建者和更新者
                diagInfoBo.setCreateBy("HIS");
                diagInfoBo.setUpdateBy("HIS");
                /*if (diagInfoVoList.size() == 0) { // 新增入院诊断
                    hisAdmittingDiagInfoService.insertByBo(diagInfoBo);
                    log.info("新增入院诊断");
                } else { // 更新入院诊断
                    diagInfoBo.setId(diagInfoVoList.get(0).getId());
                    hisAdmittingDiagInfoService.updateByBo(diagInfoBo);
                    log.info("更新入院诊断");
                }*/

                // 新增转科记录
                HisChangeDepartmentBo changeDepartmentBo = new HisChangeDepartmentBo();
                // 病历号
                changeDepartmentBo.setMedicalRecordNo(medicalRecordNo);
                // 查询转科记录
                List<HisChangeDepartmentVo> changeDepartmentVoList = hisChangeDepartmentService.queryList(changeDepartmentBo);
                // 入院科室代码
                changeDepartmentBo.setDeptCode(String.valueOf(patientHospitalInfoMap.get("PAADMAdmDeptCode")));
                // 入院时间
                changeDepartmentBo.setChangeIntoTime(DateUtil.getDateByDayAndTime(PAADMStartDate, PAADMStartTime));
                // 转入医生代码
                changeDepartmentBo.setTargDocCode(String.valueOf(patientHospitalInfoMap.get("PAADMAdmitDocCode")));
                // 转入病区代码
                changeDepartmentBo.setTargWardCode(String.valueOf(patientHospitalInfoMap.get("PAADMAdmWardCode")));
                // 转入床位代码
                changeDepartmentBo.setTargBedCode(String.valueOf(patientHospitalInfoMap.get("PAADMCurBedNo")));
                // 创建者和更新者
                changeDepartmentBo.setCreateBy("HIS");
                changeDepartmentBo.setUpdateBy("HIS");
                // 保存
                if (changeDepartmentVoList.size() == 0) {
                    hisChangeDepartmentService.insertByBo(changeDepartmentBo);
                }
            }
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }

    }

    /**
     * 住院登记
     *
     * @param data
     * @param patientBaseInfoService
     * @return
     */
    public static String InpatientEncounterStarted_bak(String data, IPatientBaseInfoService patientBaseInfoService,
                                                       IHisAdmittingDiagInfoService hisAdmittingDiagInfoService, IHisChangeDepartmentService hisChangeDepartmentService,
                                                       SysDeptMapper baseMapper) {
        try {
            Request request = getRequest(data);
            Map body1 = request.getBody();
            Map body = (Map) body1.get("InpatientEncounterStartedRt");
//        System.out.println(bodyst);
//        body = BeanUtil.toBean(bodyst, Map.class);

            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            bo.setPatientNo(String.valueOf(body.get("PATPatientID")));
            bo.setPaadmVisitNo(String.valueOf(body.get("PAADMVisitNumber")));//paadm_visit_no 就诊号码
            List<PatientBaseInfoVo> patientBaseInfoVos = patientBaseInfoService.queryList(bo);
            if (patientBaseInfoVos == null || patientBaseInfoVos.size() == 0) {
                return "1";
            }
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoVos.get(0);
            String PAADMStartDate = String.valueOf(body.get("PAADMStartDate"));//转入日期
            String PAADMStartTime = String.valueOf(body.get("PAADMStartTime"));//时间
            String PAADMAdmitDocDesc = String.valueOf(body.get("PAADMAdmitDocDesc"));//入院医生描述
            bo.setId(patientBaseInfoVo.getId());
            bo.setAdmissionTime(DateUtil.getDateByDayAndTime(PAADMStartDate, PAADMStartTime).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());//admission_time 入院时间
            bo.setDoctorName(PAADMAdmitDocDesc);
            String paadmAdmDeptCode = String.valueOf(body.get("PAADMAdmDeptCode"));//入院科室代码
            LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SysDept::getDelFlag, "0")
                .eq(ObjectUtil.isNotNull(paadmAdmDeptCode), SysDept::getHisDeptCode, paadmAdmDeptCode);

            SysDept sysDept = baseMapper.selectVoOne(lqw);
            bo.setDeptId(sysDept.getDeptId());
            //更新患者入院时间
            patientBaseInfoService.updateByBo(bo);

            //转科
            Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();//就诊码;病历号

            String paadmAdmitDocCode = String.valueOf(body.get("PAADMAdmitDocCode"));//入院医生代码

            String paadmAdmWardCode = String.valueOf(body.get("PAADMAdmWardCode"));//入院病区代码
            String paadmCurBedNo = String.valueOf(body.get("PAADMCurBedNo"));//病床号


            HisChangeDepartmentBo bo1 = new HisChangeDepartmentBo();
            bo1.setMedicalRecordNo(medicalRecordNo);//病历号
            bo1.setDeptCode(paadmAdmDeptCode);
            bo1.setChangeIntoTime(DateUtil.getDateByDayAndTime(PAADMStartDate, PAADMStartTime));
            bo1.setTargDocCode(paadmAdmitDocCode);
            bo1.setTargWardCode(paadmAdmWardCode);
            bo1.setTargBedCode(paadmCurBedNo);
            bo1.setCreateBy("HIS");
            bo1.setCreateTime(new Date());
            hisChangeDepartmentService.insertByBo(bo1);

            //诊断信息
//            String paadmDiagnoseList = String.valueOf();
            List<Map> pAADMDiagnoseList = null;
            Map map1 = (Map) body.get("PAADMDiagnoseList");
            if (map1.get("PAADMDiagnose") instanceof ArrayList) {
                pAADMDiagnoseList = (List<Map>) map1.get("PAADMDiagnose");
            } else {
                Map map2 = (Map) map1.get("PAADMDiagnose");
                pAADMDiagnoseList = new ArrayList<>();
                pAADMDiagnoseList.add(map2);
            }

            for (Map ma : pAADMDiagnoseList) {
                HisAdmittingDiagInfoBo bo2 = new HisAdmittingDiagInfoBo();
                bo2.setMedicalRecordNo(medicalRecordNo);//病历号
//                bo2.setDiagCode(String.valueOf(ma.get("PADDiagCode")));//诊断代码
                String type = "";
                if ("主诊断".equals(String.valueOf(ma.get("PADDiagType")))) {
                    type = "1";
                } else if ("出院诊断".equals(String.valueOf(ma.get("PADDiagType")))) {
                    type = "2";
                } else if ("入院诊断".equals(String.valueOf(ma.get("PADDiagType")))) {
                    type = "3";
                }
                bo2.setDiagDesc(String.valueOf(ma.get("PADDiagDesc")));//诊断描述
                bo2.setDiagType(type);//诊断类型（1主诊断 2出院诊断 3入院诊断）
                bo2.setDiagDocCode(String.valueOf(ma.get("PADDiagDocCode")));//诊断医生代码
                bo2.setDiagDocDesc(String.valueOf(ma.get("PADDiagDocDesc")));//诊断医生描述
                String type1 = "";
                if ("主要诊断".equals(String.valueOf(ma.get("PADDiagCategory")))) {
                    type1 = "1";
                } else if ("次要诊断".equals(String.valueOf(ma.get("PADDiagCategory")))) {
                    type1 = "2";
                }
                bo2.setDiagCategory(type1);//诊断级别（1主要诊断（默认第一条） 2次要诊断）
                bo2.setCreateBy("HIS");
                bo2.setCreateTime(new Date());
                hisAdmittingDiagInfoService.insertByBo(bo2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }

        return "0";
    }

    /**
     * 接收转科信息
     *
     * @param data
     * @param patientBaseInfoService
     * @param hisChangeDepartmentService
     * @return
     */
    public static String AdmTransaction_bak(String data, IPatientBaseInfoService patientBaseInfoService,
                                            IHisChangeDepartmentService hisChangeDepartmentService) {
        try {
            Request request = getRequest(data);
            Map body1 = request.getBody();
            Map body = (Map) body1.get("AdmTransactionRt");

            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            bo.setPatientNo(String.valueOf(body.get("PATPatientID")));
            bo.setPaadmVisitNo(String.valueOf(body.get("PAADMVisitNumber")));//paadm_visit_no 就诊号码
            List<PatientBaseInfoVo> patientBaseInfoVos = patientBaseInfoService.queryList(bo);
            if (patientBaseInfoVos == null || patientBaseInfoVos.size() == 0) {
                return "1";
            }
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoVos.get(0);
            Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();//就诊码;病历号
            String PAADMTState = String.valueOf(body.get("PAADMTState"));//状态 01转出02转入03换床04换医生

            //更新科室转出时间
            if ("01".equals(PAADMTState)) {
                String PAADMStartDate = String.valueOf(body.get("PAADMTStartDate"));//转出日期
                String PAADMStartTime = String.valueOf(body.get("PAADMTStartTime"));//时间
                String paadmAdmitDocCode = String.valueOf(body.get("PAADMTOrigDocCode"));//转出医生代码
                String paadmAdmDeptCode = String.valueOf(body.get("PAADMTOrigDeptCode"));//转出科室代码
                String paadmAdmWardCode = String.valueOf(body.get("PAADMTOrigWardCode"));//转出病区代码
                String paadmCurBedNo = String.valueOf(body.get("PAADMTOrigBedCode"));//病床号
                HisChangeDepartmentBo bo1 = new HisChangeDepartmentBo();
                bo1.setMedicalRecordNo(medicalRecordNo);//病历号
                bo1.setDeptCode(paadmAdmDeptCode);
                bo1.setChangeOutTime(DateUtil.getDateByDayAndTime(PAADMStartDate, PAADMStartTime));
                bo1.setTargDocCode(paadmAdmitDocCode);
                bo1.setOrigWardCode(paadmAdmWardCode);
                bo1.setOrigBedCode(paadmCurBedNo);
                bo1.setCreateBy("HIS");
                bo1.setCreateTime(new Date());
                hisChangeDepartmentService.updateByBo(bo1);
            } else if ("02".equals(PAADMTState)) { //插入科室转入时间
                String PAADMStartDate = String.valueOf(body.get("PAADMTEndDate"));//转入日期
                String PAADMStartTime = String.valueOf(body.get("PAADMTEndTime"));//时间
                String paadmAdmitDocCode = String.valueOf(body.get("PAADMAdmitDocCode"));//转入医生代码
                String paadmAdmDeptCode = String.valueOf(body.get("PAADMAdmDeptCode"));//转科室代码
                String paadmAdmWardCode = String.valueOf(body.get("PAADMAdmWardCode"));//转病区代码
                String paadmCurBedNo = String.valueOf(body.get("PAADMCurBedNo"));//病床号
                HisChangeDepartmentBo bo1 = new HisChangeDepartmentBo();
                bo1.setMedicalRecordNo(medicalRecordNo);//病历号
                bo1.setDeptCode(paadmAdmDeptCode);
                bo1.setChangeIntoTime(DateUtil.getDateByDayAndTime(PAADMStartDate, PAADMStartTime));
                bo1.setTargBedCode(paadmAdmitDocCode);
                bo1.setTargWardCode(paadmAdmWardCode);
                bo1.setTargBedCode(paadmCurBedNo);
                bo1.setCreateBy("HIS");
                bo1.setCreateTime(new Date());
                hisChangeDepartmentService.insertByBo(bo1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
        return "0";
    }

    /**
     * 接收转科信息
     *
     * @param data
     * @param patientBaseInfoService
     * @param hisChangeDepartmentService
     * @return
     */
    public static String AdmTransaction(String data, IPatientBaseInfoService patientBaseInfoService,
                                        IHisChangeDepartmentService hisChangeDepartmentService) {
        try {
            Request request = getRequest(data);
            Map body = request.getBody();
            Map changeDepartmentMap = (Map) body.get("AdmTransactionRt");
            if (ObjectUtil.isNull(changeDepartmentMap)) {
                return "1";
            }
            // 判断转诊患者是否存在
            PatientBaseInfoBo patientBaseInfoBo = new PatientBaseInfoBo();
            // 患者ID号
            patientBaseInfoBo.setPatientNo(String.valueOf(changeDepartmentMap.get("PATPatientID")));
            // 患者就诊号码
            patientBaseInfoBo.setPaadmVisitNo(String.valueOf(changeDepartmentMap.get("PAADMVisitNumber")));
            // 设置为住院状态
            patientBaseInfoBo.setPatientState(DictConstants.IN_PATIENT);
            // 查询患者基本信息
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoService.queryOne(patientBaseInfoBo);
            if (ObjectUtil.isNull(patientBaseInfoVo)) {
                return "1";
            }
            // 床号
            String bedNO = String.valueOf(changeDepartmentMap.get("PAADMTTargBedCode"));
            if (StringUtils.isNotBlank(bedNO) && !"null".equals(bedNO)) {
                patientBaseInfoVo.setBedNo(bedNO);
                PatientBaseInfoBo baseInfoBo = BeanUtil.toBean(patientBaseInfoVo, PatientBaseInfoBo.class);
                patientBaseInfoService.updateByBo(baseInfoBo);
                log.info("设置床号");
                // 主动查询HIS中的第一次生命体征接口
                // 封装参数
                Map<String, Object> params = new HashMap<>();
                params.put("code", "MES0183");
                params.put("xml", new Response().getMES0183Xml(patientBaseInfoVo.getPaadmVisitNo()));
                // 解析返回字符串
                // String hipMessageInfo = new Response().getVitalSignInfo();
                String hipMessageInfo = CXFClientUtil.sendXml("HIPMessageInfo", params);
                Request vitalSignInfoRequest = CXFClientUtil.getRequest(hipMessageInfo);
                Map vitalSignInfoBody = vitalSignInfoRequest.getBody();
                List<Map> vitalSignInfoList = null;
                Map vitalSignInfoListMap = (Map) vitalSignInfoBody.get("VitalSignInfoList");
                if (vitalSignInfoListMap.get("VitalSignInfo") instanceof ArrayList) {
                    vitalSignInfoList = (List<Map>) vitalSignInfoListMap.get("VitalSignInfo");
                } else {
                    vitalSignInfoList = new ArrayList<>();
                    vitalSignInfoList.add((Map) vitalSignInfoListMap.get("VitalSignInfo"));
                }
                // 获取患者的身高和体重
                if (ObjectUtil.isNotNull(vitalSignInfoList) && vitalSignInfoList.size() > 0) {
                    Map vitalSignInfoMap = vitalSignInfoList.get(0);
                    // 身高
                    String heightStr = String.valueOf(vitalSignInfoMap.get("height"));
                    if (StringUtils.isNotBlank(heightStr)) {
                        baseInfoBo.setPatientHeight(new BigDecimal(heightStr));
                    }
                    // 体重
                    String weightStr = String.valueOf(vitalSignInfoMap.get("Weight"));
                    if (StringUtils.isNotBlank(weightStr)) {
                        baseInfoBo.setPatientWeight(new BigDecimal(weightStr));
                    }
                    // BMI=体重（kg）÷身高的平方（m）
                    if (StringUtils.isNotBlank(heightStr) && StringUtils.isNotBlank(weightStr)) {
                        BigDecimal weight = new BigDecimal(weightStr);
                        BigDecimal heightPf = (new BigDecimal(heightStr).divide(new BigDecimal(100))).pow(2);
                        BigDecimal bmi = weight.divide(heightPf, 2, RoundingMode.UP);
                        baseInfoBo.setPatientBmi(bmi);
                    }
                    // 更新患者身高和体重数据
                    patientBaseInfoService.updateByBo(baseInfoBo);
                }
                log.info("第一次护理数据");
            }
            if ("转科".equals(String.valueOf(changeDepartmentMap.get("PAADMTState")))) { // 转科
                // 解析转出科室信息
                HisChangeDepartmentBo changeDepartmentBoOut = new HisChangeDepartmentBo();
                // 病历号
                changeDepartmentBoOut.setMedicalRecordNo(patientBaseInfoVo.getMedicalRecordNo());
                // 转出科室代码
                changeDepartmentBoOut.setDeptCode(String.valueOf(changeDepartmentMap.get("PAADMTOrigDeptCode")));
                // 查询转出科室是否存在
                List<HisChangeDepartmentVo> changeDepartmentVoList = hisChangeDepartmentService.queryList(changeDepartmentBoOut);
                // 转出日期
                String PAADMStartDate = String.valueOf(changeDepartmentMap.get("PAADMTStartDate"));
                // 转出时间
                String PAADMStartTime = String.valueOf(changeDepartmentMap.get("PAADMTStartTime"));
                if (changeDepartmentVoList.size() == 0) { // 新增转出科室记录
                    // 转出时间
                    changeDepartmentBoOut.setChangeOutTime(DateUtil.getDateByDayAndTime(PAADMStartDate, PAADMStartTime));
                    // 创建者和更新者
                    changeDepartmentBoOut.setCreateBy("HIS");
                    changeDepartmentBoOut.setUpdateBy("HIS");
                    hisChangeDepartmentService.insertByBo(changeDepartmentBoOut);
                } else { // 更新转出时间
                    HisChangeDepartmentVo hisChangeDepartmentVo = changeDepartmentVoList.get(0);
                    hisChangeDepartmentVo.setChangeOutTime(DateUtil.getDateByDayAndTime(PAADMStartDate, PAADMStartTime));
                    hisChangeDepartmentService.updateByBo(BeanUtil.toBean(hisChangeDepartmentVo, HisChangeDepartmentBo.class));
                }
                // 新增转入科室记录
                HisChangeDepartmentBo changeDepartmentBoIn = new HisChangeDepartmentBo();
                // 病历号
                changeDepartmentBoIn.setMedicalRecordNo(patientBaseInfoVo.getMedicalRecordNo());
                // 转入科室代码
                changeDepartmentBoIn.setDeptCode(String.valueOf(changeDepartmentMap.get("PAADMTTargDeptCode")));
                //转入日期
                String PAADMTEndDate = String.valueOf(changeDepartmentMap.get("PAADMTEndDate"));
                //转入时间
                String PAADMTEndTime = String.valueOf(changeDepartmentMap.get("PAADMTEndTime"));
                changeDepartmentBoIn.setChangeIntoTime(DateUtil.getDateByDayAndTime(PAADMTEndDate, PAADMTEndTime));
                hisChangeDepartmentService.insertByBo(changeDepartmentBoIn);

                // 更新床号

                log.info("转科信息");
            }
            /*else if ("分床".equals(String.valueOf(changeDepartmentMap.get("PAADMTState")))) { // 分床
                // 床号
                patientBaseInfoVo.setBedNo(String.valueOf(changeDepartmentMap.get("PAADMTTargBedCode")));
                PatientBaseInfoBo baseInfoBo = BeanUtil.toBean(patientBaseInfoVo, PatientBaseInfoBo.class);
                patientBaseInfoService.updateByBo(baseInfoBo);
                log.info("分床信息");
            }*/
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
    }

    /**
     * 接收诊断信息
     *
     * @param data
     * @param patientBaseInfoService
     * @param hisAdmittingDiagInfoService
     * @return
     */
    public static String AddDiagnosis_bak(String data, IPatientBaseInfoService patientBaseInfoService,
                                          IHisAdmittingDiagInfoService hisAdmittingDiagInfoService) {
        try {
            Request request = getRequest(data);
            Map body1 = request.getBody();
            Map body = (Map) body1.get("AddDiagnosisRt");
            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            bo.setPatientNo(String.valueOf(body.get("PATPatientID")));
            bo.setPaadmVisitNo(String.valueOf(body.get("PAADMVisitNumber")));//paadm_visit_no 就诊号码
            List<PatientBaseInfoVo> patientBaseInfoVos = patientBaseInfoService.queryList(bo);
            if (patientBaseInfoVos == null || patientBaseInfoVos.size() == 0) {
                return "1";
            }
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoVos.get(0);

            //转科
            Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();//就诊码;病历号

//            String paAdmTypeCode = String.valueOf(body.get("PAAdmTypeCode"));//就诊类型代码 用已区分O:门诊、H:体检、E:急诊病人就诊信息

            //诊断信息
            List<Map> pAADMDiagnoseList = null;
            Map map1 = (Map) body.get("PAADMDiagnoseList");
            if (map1.get("PAADMDiagnose") instanceof ArrayList) {
                pAADMDiagnoseList = (List<Map>) map1.get("PAADMDiagnose");
            } else {
                Map map2 = (Map) map1.get("PAADMDiagnose");
                pAADMDiagnoseList = new ArrayList<>();
                pAADMDiagnoseList.add(map2);
            }

            for (Map ma : pAADMDiagnoseList) {
                HisAdmittingDiagInfoBo bo2 = new HisAdmittingDiagInfoBo();
                bo2.setMedicalRecordNo(medicalRecordNo);//病历号
                String type = "";
                if ("主诊断".equals(String.valueOf(ma.get("PADDiagType")))) {
                    type = "1";
                } else if ("出院诊断".equals(String.valueOf(ma.get("PADDiagType")))) {
                    type = "2";
                } else if ("入院诊断".equals(String.valueOf(ma.get("PADDiagType")))) {
                    type = "3";
                }
//                bo2.setDiagCode(String.valueOf(ma.get("PADDiagCode")));//诊断代码
                bo2.setDiagType(type);//诊断类型（1主诊断 2出院诊断 3入院诊断）
                bo2.setDiagDesc(String.valueOf(ma.get("PADDiagDesc")));//诊断描述
                bo2.setDiagDocCode(String.valueOf(ma.get("PADDiagDocCode")));//诊断医生代码
                bo2.setDiagDocDesc(String.valueOf(ma.get("PADDiagDocDesc")));//诊断医生描述
                bo2.setDiagCategory(String.valueOf(ma.get("PADDiagCategory")));//诊断级别（1主要诊断（默认第一条） 2次要诊断）
                bo2.setCreateBy("HIS");
                bo2.setCreateTime(new Date());
                hisAdmittingDiagInfoService.insertByBo(bo2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
        return "0";
    }

    /**
     * 接收诊断信息
     *
     * @param data
     * @param patientBaseInfoService
     * @param hisAdmittingDiagInfoService
     * @return
     */
    public static String AddDiagnosis(String data, IPatientBaseInfoService patientBaseInfoService,
                                      IHisAdmittingDiagInfoService hisAdmittingDiagInfoService) {
        try {
            Request request = getRequest(data);
            Map body = request.getBody();
            Map admittingDiagInfoMap = (Map) body.get("AddDiagnosisRt");
            // 查询患者是否存在
            PatientBaseInfoBo patientBaseInfoBo = new PatientBaseInfoBo();
            patientBaseInfoBo.setPatientNo(String.valueOf(admittingDiagInfoMap.get("PATPatientID")));
            patientBaseInfoBo.setPaadmVisitNo(String.valueOf(admittingDiagInfoMap.get("PAADMVisitNumber")));
            patientBaseInfoBo.setPatientState(DictConstants.IN_PATIENT);
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoService.queryOne(patientBaseInfoBo);
            if (ObjectUtil.isNull(patientBaseInfoVo)) { // 患者没有住院信息
                return "1";
            }
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 病历号
            Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();
            // 诊断信息
            List<Map> pAADMDiagnoseList = (List<Map>) ((Map) admittingDiagInfoMap.get("PAADMDiagnoseList")).get("PAADMDiagnose");
            // 查询病历号已有的诊断信息列表
            HisAdmittingDiagInfoBo existBo = new HisAdmittingDiagInfoBo();
            existBo.setMedicalRecordNo(medicalRecordNo);
            List<HisAdmittingDiagInfoVo> existDiagInfoVoList = hisAdmittingDiagInfoService.queryList(existBo);
            // 病历号下已有的诊断代码列表
            List<String> diagCodeList = existDiagInfoVoList.stream().map(hisAdmittingDiagInfoVo -> hisAdmittingDiagInfoVo.getDiagCode()).collect(Collectors.toList());
            for (Map ma : pAADMDiagnoseList) {
                if (diagCodeList.contains(String.valueOf(ma.get("PADDiagCode")))) {
                    continue;
                }
                HisAdmittingDiagInfoBo bo = new HisAdmittingDiagInfoBo();
                //病历号
                bo.setMedicalRecordNo(medicalRecordNo);
                //诊断代码
                bo.setDiagCode(String.valueOf(ma.get("PADDiagCode")));
                // 诊断类型（1主诊断 2出院诊断 3入院诊断）
                String type = "";
                if ("主诊断".equals(String.valueOf(ma.get("PADDiagTypeDesc")))) {
                    type = "1";
                } else if ("出院诊断".equals(String.valueOf(ma.get("PADDiagTypeDesc")))) {
                    type = "2";
                } else if ("入院诊断".equals(String.valueOf(ma.get("PADDiagTypeDesc")))) {
                    type = "3";
                }
                bo.setDiagType(type);
                //诊断描述
                bo.setDiagDesc(String.valueOf(ma.get("PADDiagDesc")));
                //诊断医生代码
                bo.setDiagDocCode(String.valueOf(ma.get("PADDiagDocCode")));
                //诊断医生描述
                bo.setDiagDocDesc(String.valueOf(ma.get("PADDiagDocDesc")));
                //诊断级别（1主要诊断（默认第一条） 2次要诊断）
                bo.setDiagCategory(String.valueOf(ma.get("PADDiagCategory")));
                // 诊断日期
                String PADDiagDate = String.valueOf(ma.get("PADDiagDate"));
                // 诊断时间
                String PADDiagTime = String.valueOf(ma.get("PADDiagTime"));
                // 设置诊断时间
                bo.setDiagTime(LocalDateTime.parse(PADDiagDate + " " + PADDiagTime, dtf));
                // 诊断类型（西医、中医、证型）
                bo.setDiagCat(String.valueOf(ma.get("PADDiagCat")));
                bo.setCreateBy("HIS");
                bo.setUpdateBy("HIS");
                hisAdmittingDiagInfoService.insertByBo(bo);
            }
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
    }

    /**
     * 接收患者医嘱信息
     *
     * @param data
     * @param patientBaseInfoService
     * @param hisMedicalOrdersService
     * @return
     */
    public static String AddOrders(String data, IPatientBaseInfoService patientBaseInfoService,
                                   IHisMedicalOrdersService hisMedicalOrdersService) {
        try {
            Request request = getRequest(data);
            Map body1 = request.getBody();
            Map body = (Map) body1.get("AddOrdersRt");
            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            bo.setPatientNo(String.valueOf(body.get("PATPatientID")));
            bo.setPaadmVisitNo(String.valueOf(body.get("PAADMVisitNumber")));//paadm_visit_no 就诊号码
            List<PatientBaseInfoVo> patientBaseInfoVos = patientBaseInfoService.queryList(bo);
            if (patientBaseInfoVos == null || patientBaseInfoVos.size() == 0) {
                return "1";
            }
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoVos.get(0);

            Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();//就诊码;病历号

            List<Map> pAADMDiagnoseList = null;
            Map map1 = (Map) body.get("OEORIInfoList");
            if (map1.get("OEORIInfo") instanceof ArrayList) {
                pAADMDiagnoseList = (List<Map>) map1.get("OEORIInfo");
            } else {
                Map map2 = (Map) map1.get("OEORIInfo");
                pAADMDiagnoseList = new ArrayList<>();
                pAADMDiagnoseList.add(map2);
            }

            for (Map ma : pAADMDiagnoseList) {
                HisMedicalOrdersBo bo1 = new HisMedicalOrdersBo();
                bo1.setMedicalRecordNo(medicalRecordNo);
                bo1.setOrderItemId(String.valueOf(ma.get("OEORIOrderItemID")));        //医嘱明细ID，HIS产生单条医嘱唯一标识
                bo1.setOrderGroupId(String.valueOf(ma.get("OEORIOEORIDR")));       //医嘱组号，HIS产生同一次就诊有相同的医嘱组号
                bo1.setOrderItemCode(String.valueOf(ma.get("OEORIARCItmMastCode")));      //医嘱项目代码
                bo1.setOrderItemDesc(String.valueOf(ma.get("OEORIARCItmMastDesc")));      //医嘱项目描述
                bo1.setOrderTypeCode(String.valueOf(ma.get("OEORIPriorityDesc")));      //医嘱类型（1长期 2临时 3自备长期 4自备临时 5出院带药）
                bo1.setOrderStatus(String.valueOf(ma.get("OEORIStatusCode")));        //医嘱状态代码（V核实 E执行 D停止 C撤销）
                bo1.setOrderCategory(String.valueOf(ma.get("OEORIClass")));      //医嘱类别（1检查类 2西药类 3中药类）
                bo1.setPrescriptionNo(String.valueOf(ma.get("OEORIPrescNo")));     //处方号
                bo1.setDoseFormsCode(String.valueOf(ma.get("OEORIDoseFormsCode")));      //剂型代码
                bo1.setDoseFormsDesc(String.valueOf(ma.get("OEORIDoseFormsDesc")));      //剂型描述
                bo1.setDoseQty(String.valueOf(ma.get("OEORIDoseQty")));            //单次剂量
                bo1.setDoseUnitCode(String.valueOf(ma.get("OEORIDoseUnitCode")));       //单次剂量单位代码
                bo1.setDurationDesc(String.valueOf(ma.get("OEORIDoseUnitDesc")));       //单次剂量单位描述
                bo1.setFreqCode(String.valueOf(ma.get("OEORIFreqCode")));           //频次代码
                bo1.setFreqDesc(String.valueOf(ma.get("OEORIFreqDesc")));           //频次描述
                bo1.setInstrCode(String.valueOf(ma.get("OEORIInstrCode")));          //用药途径代码
                bo1.setInstrDesc(String.valueOf(ma.get("OEORIInstrDesc")));          //用药途径描述
                bo1.setDurationCode(String.valueOf(ma.get("OEORIDurationCode")));       //疗程代码
                bo1.setDurationDesc(String.valueOf(ma.get("OEORIDurationDesc")));       //疗程描述
                bo1.setOrderAmount(String.valueOf(ma.get("OEORIOrderQty")));        //医嘱数量
                bo1.setResultStatusCode(String.valueOf(ma.get("OEORIResultStatusCode")));   //医嘱结果状态代码
                bo1.setResultStatusDesc(String.valueOf(ma.get("OEORIResultStatusDesc")));   //医嘱结果状态描述
                bo1.setRemarks(String.valueOf(ma.get("OEORIRemarks")));            //医嘱备注信息
                bo1.setEnterDocCode(String.valueOf(ma.get("OEORIEnterDocCode")));       //医嘱开立者代码
                bo1.setEnterDocDesc(String.valueOf(ma.get("OEORIEnterDocDesc")));       //医嘱开立者描述
                bo1.setEnterTime(DateUtil.getDateByDayAndTime(String.valueOf(ma.get("OEORIEnterDate")), String.valueOf(ma.get("OEORIEnterTime"))).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());                 //医嘱开立时间
                bo1.setEnterDeptCode(String.valueOf(ma.get("OEORIEnterDeptCode")));      //医嘱开立科室代码
                bo1.setEnterDeptDesc(String.valueOf(ma.get("OEORIEnterDeptDesc")));      //医嘱开立科室
                bo1.setExecDeptCode(String.valueOf(ma.get("OEORIExecDeptCode")));       //医嘱执行科室代码
                bo1.setExecDeptDesc(String.valueOf(ma.get("OEORIExecDeptDesc")));       //医嘱执行科室
                //bo1.setRequireExecTime(DateUtil.getDateByDayAndTime(String.valueOf(ma.get("OEORIRequireExecDate")), String.valueOf(ma.get("OEORIRequireExecTime"))).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());           //要求执行时间
                //bo1.setStopTime(DateUtil.getDateByDayAndTime(String.valueOf(ma.get("OEORIStopDate")), String.valueOf(ma.get("OEORIStopTime"))).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());                  //医嘱停止时间
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String OEORIRequireExecDate = String.valueOf(ma.get("OEORIRequireExecDate")); // 要求执行日期
                String OEORIRequireExecTime = String.valueOf(ma.get("OEORIRequireExecTime")); // 要求执行时间
                if (StringUtils.isNotBlank(OEORIRequireExecDate) && StringUtils.isNotBlank(OEORIRequireExecTime)) {
                    bo1.setRequireExecTime(LocalDateTime.parse(OEORIRequireExecDate + " " + OEORIRequireExecTime, dtf)); // 要求执行时间
                }
                String OEORIStopDate = String.valueOf(ma.get("OEORIStopDate")); // 医嘱停止日期
                String OEORIStopTime = String.valueOf(ma.get("OEORIStopTime")); // 医嘱停止时间
                if (StringUtils.isNotBlank(OEORIStopDate) && StringUtils.isNotBlank(OEORIStopTime)) {
                    bo1.setStopTime(LocalDateTime.parse(OEORIStopDate + " " + OEORIStopTime, dtf)); // 医嘱停止时间
                } else { // 计算医嘱停止时间
                    LocalDateTime requireExecTime = bo1.getRequireExecTime();
                    Integer days = 1; // 用药天数
                    String durationCode = String.valueOf(ma.get("OEORIDurationCode")); // 疗程
                    if (StringUtils.isNotBlank(durationCode)) {
                        if (durationCode.contains("天")) {
                            days = Integer.valueOf(durationCode.split("天")[0]);
                        } else if (durationCode.contains("付")) {
                            days = Integer.valueOf(durationCode.split("付")[0]);
                        }
                    }
                    bo1.setStopTime(requireExecTime.plusDays(days));
                }
                bo1.setStopDocCode(String.valueOf(ma.get("OEORIStopDocCode")));        //停止医嘱者代码
                bo1.setStopDocDesc(String.valueOf(ma.get("OEORIStopDocDesc")));        //停止医嘱者描述
                bo1.setIsSkinTest(String.valueOf(ma.get("OEORIIsSkinTest")));         //是否皮试（Y是 N否）
                bo1.setIsEmergency(String.valueOf(ma.get("OEORIISEmergency")));        //是否紧急（Y是 N否）
                bo1.setParentOrderId(String.valueOf(ma.get("OEORIParentOrderID")));      //父医嘱ID
                bo1.setSpecimenId(String.valueOf(ma.get("OEORISpecimenID")));         //标本号
                bo1.setSpecimenCode(String.valueOf(ma.get("OEORISpecimenCode")));       //标本代码
                bo1.setOrderPrice(String.valueOf(ma.get("OEORIPrice")));         //医嘱价格
                bo1.setSpeedFlowRate(String.valueOf(ma.get("OEORISpeedFlowRate")));      //流速
                bo1.setFlowRateUnitDesc(String.valueOf(ma.get("OEORIFlowRateUnitdesc")));   //流速单位
                bo1.setBloodNum(String.valueOf(ma.get("OEORIBloodNum")));           //血袋号
                bo1.setIsPreseCookMode(String.valueOf(ma.get("DHCQuePrescCookMode")));    //是否代煎（Y是 N否）
                bo1.setCmPrescCookTypeCode(String.valueOf(ma.get("DHCQueCMPrescTypeCode")));//草药剂型
                bo1.setPackUomDesc(String.valueOf(ma.get("OEORIPackUOMDesc")));        //数量单位
                bo1.setUpdateUserCode(String.valueOf(ma.get("UpdateUserCode")));     //最后更新人编码
                bo1.setUpdateUserDesc(String.valueOf(ma.get("UpdateUserDesc")));     //最后更新人描述
                bo1.setUpdateLastTime(DateUtil.getDateByDayAndTime(String.valueOf(body.get("UpdateDate")), String.valueOf(body.get("UpdateTime"))).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());            //最后更新时间
                hisMedicalOrdersService.insertByBo(bo1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }

        return "0";
    }

    /**
     * 医嘱状态变更
     *
     * @param data
     * @param patientBaseInfoService
     * @param hisMedicalOrdersService
     * @return
     */
    public static String UpdateOrdersStatus(String data, IPatientBaseInfoService patientBaseInfoService, IHisMedicalOrdersService hisMedicalOrdersService) {
        try {
            /*Request request = getRequest(data);
            Map body = request.getBody();
            Map updateOrdersMap = (Map) body.get("UpdateOrdersRt");
            // 查询患者住院信息信息
            PatientBaseInfoBo patientBaseInfoBo = new PatientBaseInfoBo();
            // 患者ID号
            patientBaseInfoBo.setPatientNo(String.valueOf(updateOrdersMap.get("PATPatientID")));
            // 患者就诊号码
            patientBaseInfoBo.setPaadmVisitNo(String.valueOf(updateOrdersMap.get("PAADMVisitNumber")));
            // 患者住院状态
            patientBaseInfoBo.setPatientState(DictConstants.IN_PATIENT);
            List<PatientBaseInfoVo> patientBaseInfoVoList = patientBaseInfoService.queryList(patientBaseInfoBo);
            if (ObjectUtil.isNull(patientBaseInfoVoList) || patientBaseInfoVoList.size() == 0) {
                return "1";
            }

            // 获取医嘱变更列表
            List<Map> updateOrdersList = new ArrayList<>();
            Map map = (Map) updateOrdersMap.get("OEORIInfoList");
            if (map.get("OEORIInfo") instanceof ArrayList) {
                updateOrdersList = (List<Map>) map.get("OEORIInfo");
            } else {
                Map map2 = (Map) map.get("OEORIInfo");
                updateOrdersList.add(map2);
            }

            // 医嘱状态变更
            for (Map OEORIInfo : updateOrdersList) {
                // 医嘱明细ID
                String OEORIOrderItemID = String.valueOf(OEORIInfo.get("OEORIOrderItemID"));
                // 查询医嘱
                if (StringUtils.isNotBlank(OEORIOrderItemID)) {
                    HisMedicalOrdersBo hisMedicalOrdersBo = new HisMedicalOrdersBo();
                    hisMedicalOrdersBo.setOrderItemId(OEORIOrderItemID);
                    HisMedicalOrders hisMedicalOrders = hisMedicalOrdersService.queryByOrderItemId(OEORIOrderItemID);
                    if (ObjectUtil.isNull(hisMedicalOrders)) {
                        continue;
                    }
                    // 停止日期
                    String OEORIXDate = String.valueOf(OEORIInfo.get("OEORIXDate"));
                    // 停止时间
                    String OEORIXTime = String.valueOf(OEORIInfo.get("OEORIXTime"));
                    // 设置医嘱停止时间
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    hisMedicalOrders.setStopTime(LocalDateTime.parse(OEORIXDate + " " + OEORIXTime, dtf));
                    hisMedicalOrdersService.updateByBo(BeanUtil.toBean(hisMedicalOrders, HisMedicalOrdersBo.class));
                }
            }*/
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
    }

    /**
     * 生命体征
     *
     * @param data
     * @param patientBaseInfoService
     * @param pharmaceuticalCareDetailMapper
     * @return
     */
    public static String SaveVitalSigns(String data, IPatientBaseInfoService patientBaseInfoService,
                                        PharmaceuticalCareDetailMapper pharmaceuticalCareDetailMapper) {
        try {
            Request request = getRequest(data);
            Map body1 = request.getBody();
            Map body = (Map) body1.get("VitalSignRt");
            PatientBaseInfoBo bo = new PatientBaseInfoBo();
            bo.setPatientNo(String.valueOf(body.get("PATPatientID")));
            bo.setPaadmVisitNo(String.valueOf(body.get("PAADMVisitNumber")));//paadm_visit_no 就诊号码
            List<PatientBaseInfoVo> patientBaseInfoVos = patientBaseInfoService.queryList(bo);
            if (patientBaseInfoVos == null || patientBaseInfoVos.size() == 0) {
                return "1";
            }
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoVos.get(0);
            Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();//就诊码;病历号

            /*List<Map> pAADMDiagnoseList = null;
            Map map1 = (Map) body.get("VitalSignInfoList");
            if (map1.get("VitalSignInfo") instanceof ArrayList) {
                pAADMDiagnoseList = (List<Map>) map1.get("VitalSignInfo");
            } else {
                Map map2 = (Map) map1.get("VitalSignInfo");
                pAADMDiagnoseList = new ArrayList<>();
                pAADMDiagnoseList.add(map2);
            }

            for (Map ma : pAADMDiagnoseList) {
                HisVitalSignsBo bo1 = new HisVitalSignsBo();
                bo1.setMedicalRecordNo(medicalRecordNo);
                Map temperature = (Map) ma.get("Temperature");
                Set<String> set = temperature.keySet();
                String[] keyset = set.toArray(new String[set.size()]);
                bo1.setSignType(keyset[0]);//体征类型（脉搏Pulse 呼吸Breathing 收缩压SystolicBP 舒张压DiastolicBP 体温 Temperature）
                bo1.setSignResult(String.valueOf(ma.get(keyset[0])));//体征结果
                bo1.setMeasureUserCode(String.valueOf(ma.get("MeasureUserCod")));//测量人工号
                bo1.setMeasureTime(DateUtil.getDateByDayAndTime(String.valueOf(ma.get("MeasureDate")), String.valueOf(ma.get("MeasureTime"))));
                hisVitalSignsService.insertByBo(bo1);
            }*/

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Map vitalSignInfoMap = (Map) ((Map) body.get("VitalSignInfoList")).get("VitalSignInfo");
            // 获取护理日期
            String measureDateStr = (String) vitalSignInfoMap.get("MeasureDate");
            LocalDate measureDate = LocalDate.parse(measureDateStr, formatter);
            // 获取护理时间
            String measureTimeStr = (String) vitalSignInfoMap.get("MeasureTime");
            // 查询药学监护详情，来源自HIS
            PharmaceuticalCareDetail pharmaceuticalCareDetail = pharmaceuticalCareDetailMapper.selectOne(new LambdaQueryWrapper<PharmaceuticalCareDetail>()
                .eq(PharmaceuticalCareDetail::getMedicalRecordNo, medicalRecordNo)
                .eq(PharmaceuticalCareDetail::getCareDate, measureDate)
                .eq(PharmaceuticalCareDetail::getCreateBy, "HIS"));
            if (ObjectUtil.isNull(pharmaceuticalCareDetail)) { // 不存在
                // 创建药学监护详情实体对象
                pharmaceuticalCareDetail = new PharmaceuticalCareDetail();
                // 病历号
                pharmaceuticalCareDetail.setMedicalRecordNo(medicalRecordNo);
                // 护理日期
                pharmaceuticalCareDetail.setCareDate(measureDate);
                // 入院天数
                pharmaceuticalCareDetail.setInHospitalDays((int) (patientBaseInfoVo.getAdmissionTime().toLocalDate().until(measureDate, ChronoUnit.DAYS)) + 1);
                // 创建对象信息
                pharmaceuticalCareDetail.setCreateBy("HIS");
                pharmaceuticalCareDetail.setUpdateBy("HIS");
            }
            // 解析生命体征数据
            String info = null;
            // 体温
            if (ObjectUtil.isNotNull(vitalSignInfoMap.get("Temperature"))) {
                info = "体温：" + vitalSignInfoMap.get("Temperature") + "℃" + " 时间：" + measureTimeStr;
            }
            // 脉搏（心率）
            if (ObjectUtil.isNotNull(vitalSignInfoMap.get("Pulse"))) {
                info = "心率：" + vitalSignInfoMap.get("Pulse") + "次/分" + " 时间：" + measureTimeStr;
            }
            // 呼吸
            if (ObjectUtil.isNotNull(vitalSignInfoMap.get("Breathing"))) {
                info = "呼吸：" + vitalSignInfoMap.get("Breathing") + "次/分" + " 时间：" + measureTimeStr;
            }
            // 收缩压
            if (ObjectUtil.isNotNull(vitalSignInfoMap.get("SystolicBP"))) {
                info = "收缩压：" + vitalSignInfoMap.get("SystolicBP") + "mmhg-毫米汞柱" + " 时间：" + measureTimeStr;
            }
            // 舒张压
            if (ObjectUtil.isNotNull(vitalSignInfoMap.get("DiastolicBP"))) {
                info = "舒张压：" + vitalSignInfoMap.get("DiastolicBP") + "mmhg-毫米汞柱" + " 时间：" + measureTimeStr;
            }
            // 更新生命体征数据
            if (StringUtils.isNotBlank(info)) {
                StringBuilder sb = new StringBuilder();
                String vitalSigns = pharmaceuticalCareDetail.getVitalSigns();
                if (StringUtils.isNotBlank(vitalSigns)) { // 已存在
                    sb.append(vitalSigns);
                    sb.append("、" + info);
                } else { // 不存在
                    sb.append(info);
                }
                pharmaceuticalCareDetail.setVitalSigns(sb.toString());
            }
            // 新增或更新药学监护详情
            pharmaceuticalCareDetailMapper.insertOrUpdate(pharmaceuticalCareDetail);
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
    }


    /**
     * 患者出院
     *
     * @param data
     * @param patientBaseInfoService
     * @param hisChangeDepartmentService
     * @return
     */
    public static String InpatientDischarge(String data, IPatientBaseInfoService patientBaseInfoService,
                                            IHisChangeDepartmentService hisChangeDepartmentService) {

        Request request = getRequest(data);
        Map body1 = request.getBody();
        Map body = (Map) body1.get("InpatientDischargeRt");

        PatientBaseInfoBo bo = new PatientBaseInfoBo();
        bo.setPatientNo(String.valueOf(body.get("PATPatientID")));
        bo.setPaadmVisitNo(String.valueOf(body.get("PAADMVisitNumber")));//paadm_visit_no 就诊号码
        List<PatientBaseInfoVo> patientBaseInfoVos = patientBaseInfoService.queryList(bo);
        if (patientBaseInfoVos == null || patientBaseInfoVos.size() == 0) {
            return "1";
        }
        PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoVos.get(0);
        bo.setId(patientBaseInfoVo.getId());
        // 住院状态
        bo.setPatientState("1");
        // HIS出院日期
        String paadmEndDate = String.valueOf(body.get("PAADMEndDate"));
        // HIS出院时间
        String paadmEndTime = String.valueOf(body.get("PAADMEndTime"));
        // 设置患者出院时间
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        bo.setDischargeTime(LocalDateTime.parse(paadmEndDate + " " + paadmEndTime, dtf));
        patientBaseInfoService.updateByBo(bo);
        Integer medicalRecordNo = patientBaseInfoVo.getMedicalRecordNo();//就诊码;病历号
        //查询最后转科记录
        HisChangeDepartmentVo vo = hisChangeDepartmentService.selectByMedicalRecordNoAnd(medicalRecordNo);
        String paadmDisDeptCode = String.valueOf(body.get("PAADMDisDeptCode"));
        String paadmDisStatusCode = String.valueOf(body.get("PAADMDisStatusCode"));
//        vo.setOrigBedCode("");//转出床位代码
//        vo.setOrigDocCode("");//转出医生代码
//        vo.setOrigRoomCode("");//转出房间代码
        vo.setOrigWardCode(paadmDisDeptCode);//转出病区代码
        vo.setChangeOutTime(DateUtil.getDateByDayAndTime(paadmEndDate, paadmEndTime));

        //更新转科记录
        HisChangeDepartmentBo hisChangeDepartmentBo = BeanUtil.toBean(vo, HisChangeDepartmentBo.class);
        hisChangeDepartmentService.updateByBo(hisChangeDepartmentBo);
        return "0";
    }

    /**
     * 维护药品库存信息
     *
     * @param data                      药品库存数据
     * @param hisMedicineStorageService
     * @return
     */
    public static String maintainHisMedicineStorage(String data, IHisMedicineStorageService hisMedicineStorageService) {
        try {
            // 查询电子药历药品库存列表
            List<HisMedicineStorageVo> medicineStorageVoList = hisMedicineStorageService.queryList(new HisMedicineStorageBo());
            // 解析药品信息
            Request request = getRequest(data);
            Map body = request.getBody();
            // List<Map> CTMedicalStockList = (List<Map>) ((Map) body.get("CT_MedicalStockList")).get("CT_MedicalStock");
            List<Map> CTMedicalStockList = null;
            Map CTMedicalStockListMap = (Map) body.get("CT_MedicalStockList");
            if (CTMedicalStockListMap.get("CT_MedicalStock") instanceof ArrayList) {
                CTMedicalStockList = (List<Map>) CTMedicalStockListMap.get("CT_MedicalStock");
            } else {
                Map CTMedicalStockMap = (Map) CTMedicalStockListMap.get("CT_MedicalStock");
                CTMedicalStockList = new ArrayList<>();
                CTMedicalStockList.add(CTMedicalStockMap);
            }
            // 新增或修改药品库存信息
            List<HisMedicineStorage> hisMedicineStorageList = new ArrayList<>();
            if (ObjectUtil.isNotNull(CTMedicalStockList)) {
                CTMedicalStockList.stream().forEach(map -> {
                    // 封装药品库存实体对象
                    HisMedicineStorage hisMedicineStorage = new HisMedicineStorage();
                    hisMedicineStorage.setMedicalCode(String.valueOf(map.get("CTPHDMI_Code"))); // 药品编号（药品在HIS中的唯一标志）
                    hisMedicineStorage.setMedicineName(String.valueOf(map.get("CTPHDMI_Desc"))); // 药品名称
                    // hisMedicineStorage.setMedicineHouse(String.valueOf("")); // 所在药房
                    hisMedicineStorage.setIsBaseMedicine(String.valueOf(map.get("CTPHDMS_StateBasicDryFlag"))); // 是否基药
                    hisMedicineStorage.setMedicineSpec(String.valueOf(map.get("CTPHDMS_Spec"))); // 药品规格
                    hisMedicineStorage.setProductFactory(String.valueOf(map.get("CTPHDMI_ManufacturerDesc"))); // 生产厂家
                    for (HisMedicineStorageVo hisMedicineStorageVo : medicineStorageVoList) { // 如果药品已存在，就给药品实体对象设置ID
                        if (hisMedicineStorageVo.getMedicalCode().equals(map.get("CTPHDMI_Code"))) {
                            hisMedicineStorage.setId(hisMedicineStorageVo.getId());
                            break;
                        }
                    }
                    hisMedicineStorageList.add(hisMedicineStorage);
                });
            }
            hisMedicineStorageService.insertOrUpdateBatch(hisMedicineStorageList);
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return "1";
        }
    }

    /**
     * 维护库存药品的价格和单位
     *
     * @param data
     * @param hisMedicineStorageService
     * @return
     */
    public static String updateMedicineStoragePriceAndUnit(String data, IHisMedicineStorageService hisMedicineStorageService) {
        try {
            // 查询电子药历药品库存列表
            List<HisMedicineStorageVo> medicineStorageVoList = hisMedicineStorageService.queryList(new HisMedicineStorageBo());
            // 解析药品价格和单位信息
            Request request = getRequest(data);
            Map body = request.getBody();
            List<Map> CTARCItmMastList = null;
            Map CTARCItmMastListMap = (Map) body.get("CT_ARCItmMastList");
            if (CTARCItmMastListMap.get("CT_ARCItmMast") instanceof ArrayList) {
                CTARCItmMastList = (List<Map>) CTARCItmMastListMap.get("CT_ARCItmMast");
            } else {
                CTARCItmMastList = new ArrayList<>();
                CTARCItmMastList.add((Map) CTARCItmMastListMap.get("CT_ARCItmMast"));
            }
            // 更新药品价格和单位
            List<HisMedicineStorage> hisMedicineStorageList = new ArrayList<>();
            if (ObjectUtil.isNotNull(CTARCItmMastList)) {
                CTARCItmMastList.stream().forEach(map -> {
                    // 判断库房是否存在药品
                    for (HisMedicineStorageVo hisMedicineStorageVo : medicineStorageVoList) { // 如果药品已存在，就给药品实体对象设置ID
                        if (hisMedicineStorageVo.getMedicalCode().equals(map.get("CTARCIM_Code"))) {
                            hisMedicineStorageVo.setMedicinePrice(String.valueOf(map.get("CTARCIM_Price"))); // 价格
                            hisMedicineStorageVo.setMeterUnit(String.valueOf(map.get("CTARCIM_Unit"))); // 计量单位
                            hisMedicineStorageList.add(BeanUtil.toBean(hisMedicineStorageVo, HisMedicineStorage.class));
                            break;
                        }
                    }
                });
            }
            hisMedicineStorageService.insertOrUpdateBatch(hisMedicineStorageList);
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return "1";
        }
    }

    /**
     * 接收检验结果
     *
     * @param data
     * @param firstLevelMapper
     * @param twoLevelMapper
     * @return
     */
    public static String receiveInspection(String data, IPatientBaseInfoService patientBaseInfoService, FirstLevelMapper firstLevelMapper, TwoLevelMapper twoLevelMapper) {
        try {
            // 解析检验结果文档信息
            Request request = getRequest(data);
            Map body = request.getBody();
            Map registerDocumentRtMap = (Map) body.get("RegisterDocumentRt");
            String patPatientID = String.valueOf(registerDocumentRtMap.get("PATPatientID")); // 患者ID
            String PAADMVisitNumber = String.valueOf(registerDocumentRtMap.get("PAADMVisitNumber")); // 就诊号
            // 查询患者住院信息
            PatientBaseInfoBo patientBaseInfoBo = new PatientBaseInfoBo();
            patientBaseInfoBo.setPatientNo(patPatientID);
            patientBaseInfoBo.setPaadmVisitNo(PAADMVisitNumber);
            PatientBaseInfoVo patientBaseInfoVo = patientBaseInfoService.queryOne(patientBaseInfoBo);
            if (ObjectUtil.isNull(patientBaseInfoVo)) {
                return "0";
            }
            // 解密文档内容，解析检验结果数据
            String DocumentContent = String.valueOf(registerDocumentRtMap.get("DocumentContent")); // 检验结果文档（base64加密）
            String resultXml = Base64.decodeStr(DocumentContent);
            // 解析检验结果报文信息
            Request requestXml = getRequest(resultXml);
            Map structuredBody = requestXml.getStructuredBody();
            List<Map<String, Object>> outSectionList = (List) structuredBody.get("section");
            // 循环外层部分列表
            outSectionList.stream().forEach(out -> {
                String e02 = String.valueOf(out.get("E02"));
                // 跳过诊断
                if ("诊断代码".equals(e02)) {
                    return;
                }
                // 解析血常规、肝功能基础或肾功能基础化验单
                if (e02.contains("血常规") || e02.contains("肝功能基础") || e02.contains("肾功能基础")) {
                    // 查询一级监护信息对象
                    FirstLevel firstLevel = firstLevelMapper.selectOne(new LambdaQueryWrapper<FirstLevel>().eq(FirstLevel::getMedicalRecordNo, patientBaseInfoVo.getMedicalRecordNo()));
                    if (ObjectUtil.isNull(firstLevel)) {
                        firstLevel = new FirstLevel();
                        firstLevel.setMedicalRecordNo(patientBaseInfoVo.getMedicalRecordNo());
                    }
                    // 查询二级监护信息对象
                    TwoLevel twoLevel = twoLevelMapper.selectOne(new LambdaQueryWrapper<TwoLevel>().eq(TwoLevel::getMedicalRecordNo, patientBaseInfoVo.getMedicalRecordNo()));
                    if (ObjectUtil.isNull(twoLevel)) {
                        twoLevel = new TwoLevel();
                        twoLevel.setMedicalRecordNo(patientBaseInfoVo.getMedicalRecordNo());
                    }
                    // 获取检验结果列表
                    List<Map<String, Object>> innerSectionList = (List) out.get("section");
                    // 循环内层部分列表，解析出检验子项目和结果
                    for (Map inner : innerSectionList) {
                        // 跳过图像信息
                        if ("图像信息的详细描述".equals(inner.get("text"))) {
                            continue;
                        }
                        // 获取检验子项结果
                        String itemName = String.valueOf(inner.get("E02")); // 检验子项名称
                        String itemValue = String.valueOf(inner.get("text")); // 检验子项结果
                        // Cr 肌酐
                        if ("肌酐".equals(itemName)) {
                            firstLevel.setRenalFunction(itemValue);
                            twoLevel.setModerateRenalFunction(itemValue);
                        }
                        // ALT 丙氨酸氨基转移酶
                        if ("丙氨酸氨基转移酶".equals(itemName)) {
                            firstLevel.setAltValue(itemValue);
                            twoLevel.setAltValue(itemValue);
                        }
                        // AST 天冬氨酸氨基转移酶
                        if ("天冬氨酸氨基转移酶".equals(itemName)) {
                            firstLevel.setAstValue(itemValue);
                            twoLevel.setAstValue(itemValue);
                        }
                        // ALP 碱性磷酸酶
                        if ("碱性磷酸酶".equals(itemName)) {
                            firstLevel.setAlpValue(itemValue);
                            twoLevel.setAlpValue(itemValue);
                        }
                        // T-BiL 总胆红素
                        if ("总胆红素".equals(itemName)) {
                            firstLevel.setTbil(itemValue);
                            twoLevel.setTbil(itemValue);
                        }
                    }
                    // 同时伴有中度肾功能不全（30ml/min＜Clcr≤60ml/min）和中度肝功能不全（生化指标ALT或 AST＞2~4ULN orALP＞2~4ULN orT-BiL＞2~3ULN ，或CTP 评分＞7~9 分者）；
                    if (patientBaseInfoVo.getPatientAge() >= 18
                        && ObjectUtil.isNotNull(patientBaseInfoVo.getPatientWeight())
                        && StringUtils.isNotBlank(firstLevel.getRenalFunction())) {
                        // 计算Clcr值
                        double clcr = (140 - patientBaseInfoVo.getPatientAge()) * patientBaseInfoVo.getPatientWeight().intValue() / (72 * Double.parseDouble(firstLevel.getRenalFunction()));
                        // 判断性别
                        if ("2".equals(patientBaseInfoVo.getPatientSex())) { // 女性
                            clcr = clcr * 0.85;
                        }
                        // 中度肾功能不全（30ml/min＜Clcr≤60ml/min）
                        if (clcr > 30 && clcr < 60) {
                            // 中度肝功能不全（生化指标ALT或 AST＞2~4ULN orALP＞2~4ULN orT-BiL＞2~3ULN ，或CTP 评分＞7~9 分者）
                            // ALT
                            String altValue = firstLevel.getAltValue();
                            if (StringUtils.isNotBlank(altValue)) {
                                // 中度
                                if (Double.parseDouble(altValue) > 2 && Double.parseDouble(altValue) <= 4) {
                                    firstLevel.setBothValue("1");
                                }
                            }
                            // AST
                            String astValue = firstLevel.getAstValue();
                            if (StringUtils.isNotBlank(astValue)) {
                                // 中度
                                if (Double.parseDouble(astValue) > 2 && Double.parseDouble(astValue) <= 4) {
                                    firstLevel.setBothValue("1");
                                }
                            }
                            // ALP
                            String alpValue = firstLevel.getAlpValue();
                            if (StringUtils.isNotBlank(alpValue)) {
                                // 中度
                                if (Double.parseDouble(alpValue) > 2 && Double.parseDouble(alpValue) <= 4) {
                                    firstLevel.setBothValue("1");
                                }
                            }
                            // T-BiL
                            String tbilValue = firstLevel.getTbil();
                            if (StringUtils.isNotBlank(tbilValue)) {
                                // 中度
                                if (Double.parseDouble(tbilValue) > 2 && Double.parseDouble(tbilValue) <= 3) {
                                    firstLevel.setBothValue("1");
                                }
                            }
                        } else { // 非中度肾功能不全
                            firstLevel.setBothValue("0");
                        }
                    }
                    // 非中度肝功能不全
                    if (StringUtils.isNotBlank(firstLevel.getAltValue())
                        && StringUtils.isNotBlank(firstLevel.getAstValue())
                        && StringUtils.isNotBlank(firstLevel.getAlpValue())
                        && StringUtils.isNotBlank(firstLevel.getTbil())) {
                        if ((Double.parseDouble(firstLevel.getAltValue()) <= 2 && Double.parseDouble(firstLevel.getAltValue()) > 4)
                            || (Double.parseDouble(firstLevel.getAstValue()) <= 2 && Double.parseDouble(firstLevel.getAstValue()) > 4)
                            || (Double.parseDouble(firstLevel.getAlpValue()) <= 2 && Double.parseDouble(firstLevel.getAlpValue()) > 4)
                            || (Double.parseDouble(firstLevel.getTbil()) <= 2 && Double.parseDouble(firstLevel.getTbil()) > 3)) {
                            firstLevel.setBothValue("0");
                        }
                    }

                    // 更新或新增一级监护信息
                    firstLevelMapper.insertOrUpdate(firstLevel);
                    // 更新或新增二级监护信息
                    twoLevelMapper.insertOrUpdate(twoLevel);
                    // 判断患者的监护级别
                    PatientBaseInfo patientBaseInfo = BeanUtil.toBean(patientBaseInfoVo, PatientBaseInfo.class);
                    // 一级监护
                    boolean isFirst = CareLevelUtil.isFirstCareLevel(patientBaseInfo, firstLevel);
                    if (isFirst) {
                        patientBaseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_THREE);
                    }
                    // 二级监护
                    boolean isTwo = CareLevelUtil.isTwoCareLevel(patientBaseInfo, twoLevel);
                    if (!isFirst && isTwo) {
                        patientBaseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_TWO);
                    }
                    // 三级监护
                    if (!isFirst && !isTwo) {
                        patientBaseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_ONE);
                    }
                    // 更新患者监护级别
                    patientBaseInfoService.updateByBo(BeanUtil.toBean(patientBaseInfo, PatientBaseInfoBo.class));
                }
            });

            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return "1";
        }
    }

    public static Request<T> getRequest(String data) {
        Map map = XmlUtil.xmlToMap(data);
        Request request = BeanUtil.toBean(map, Request.class);
        return request;
    }


    public static void main(String[] args) {
        String xml = "<Request>\n" +
            "    <Header>\n" +
            "        <SourceSystem>1</SourceSystem>\n" +
            "        <MessageID>1</MessageID>\n" +
            "    </Header>\n" +
            "    <Body>\n" +
            "        <InpatientEncounterStartedRt>\n" +
            "            <PATPatientID>1</PATPatientID>\n" +
            "            <PAADMVisitNumber>1</PAADMVisitNumber>\n" +
            "            <PAADMEncounterTypeCode>1</PAADMEncounterTypeCode>\n" +
            "            <PAADMEncounterTypeDesc>1</PAADMEncounterTypeDesc>\n" +
            "            <FeeTypeCode>1</FeeTypeCode>\n" +
            "            <FeeTypeDesc>1</FeeTypeDesc>\n" +
            "            <PAADMVisitTimes>1</PAADMVisitTimes>\n" +
            "            <PAADMAdmitDocCode>1</PAADMAdmitDocCode>\n" +
            "            <PAADMAdmitDocDesc>1</PAADMAdmitDocDesc>\n" +
            "            <PAADMStartDate>1</PAADMStartDate>\n" +
            "            <PAADMStartTime>1</PAADMStartTime>\n" +
            "            <PAADMAdmDeptCode>1</PAADMAdmDeptCode>\n" +
            "            <PAADMAdmDeptDesc>1</PAADMAdmDeptDesc>\n" +
            "            <PAADMAdmWardCode>1</PAADMAdmWardCode>\n" +
            "            <PAADMAdmWardDesc>1</PAADMAdmWardDesc>\n" +
            "            <PAADMCurBedNo>1</PAADMCurBedNo>\n" +
            "            <PAADMDiagnoseList>\n" +
            "                <PAADMDiagnose>\n" +
            "                    <PADDiagCode>1</PADDiagCode>\n" +
            "                    <PADDiagDesc>1</PADDiagDesc>\n" +
            "                    <PADDiagType>1</PADDiagType>\n" +
            "                    <PADDiagDocCode>1</PADDiagDocCode>\n" +
            "                    <PADDiagDocDesc>1</PADDiagDocDesc>\n" +
            "                    <PADDiagCategory>1</PADDiagCategory>\n" +
            "                    <PADDiagDate>1</PADDiagDate>\n" +
            "                    <PADDiagTime>1</PADDiagTime>\n" +
            "                    <PADRemarks>1</PADRemarks>\n" +
            "                </PAADMDiagnose>\n" +
            "                <PAADMDiagnose>\n" +
            "                    <PADDiagCode>1</PADDiagCode>\n" +
            "                    <PADDiagDesc>1</PADDiagDesc>\n" +
            "                    <PADDiagType>1</PADDiagType>\n" +
            "                    <PADDiagDocCode>1</PADDiagDocCode>\n" +
            "                    <PADDiagDocDesc>1</PADDiagDocDesc>\n" +
            "                    <PADDiagCategory>1</PADDiagCategory>\n" +
            "                    <PADDiagDate>1</PADDiagDate>\n" +
            "                    <PADDiagTime>1</PADDiagTime>\n" +
            "                    <PADRemarks>1</PADRemarks>\n" +
            "                </PAADMDiagnose>\n" +
            "            </PAADMDiagnoseList>\n" +
            "            <UpdateUserCode>1</UpdateUserCode>\n" +
            "            <UpdateDate>1</UpdateDate>\n" +
            "            <UpdateTime>1</UpdateTime>\n" +
            "        </InpatientEncounterStartedRt>\n" +
            "    </Body>\n" +
            "</Request>";


        Request request = getRequest(xml);
        Map<String, String> body = request.getBody();
        String bodyst = body.get("InpatientEncounterStartedRt");
        System.out.println(bodyst);
        bodyst = bodyst.replaceAll("=", ":");

        Map map = JSONUtil.toBean(bodyst, Map.class);
        String paadmDiagnoseList = String.valueOf(map.get("PAADMDiagnoseList"));
        List<Map> maps = null;
        Map map1 = JSONUtil.toBean(paadmDiagnoseList, Map.class);
        if (map1.get("PAADMDiagnose") instanceof ArrayList) {
//            maps = (List<Map>) map1.get("PAADMDiagnose"));
        } else {
            Map map2 = JSONUtil.toBean(String.valueOf(map1.get("PAADMDiagnose")), Map.class);
            maps = new ArrayList<>();
            maps.add(map2);
        }
        for (Map ma : maps) {
            Object[] set = ma.keySet().toArray();
            for (int i = 0; i < set.length; i++) {
                System.out.println(set[i]);
                System.out.println(ma.get(set[i]));
            }
            System.out.println("**********");
        }
        System.out.println();
    }
}
